<!-- 商户报表 -->
<template>
  <SearchTable :query="data.query" :list="data.list" :total="data.total" :showPanel="false" :showExport="true"
    @changeSize="changeSize" @download="getExport" @changePage="changePage" @search="getSearchList"
    @reset="onHideDetails(true)" @changeTh="data.dialogVisible = true">
    <template #form>
      <Operator ref="OperatorRef" @query="queryItem" />
      <el-form-item label="日期时间：">
        <el-date-picker v-model="data.query.date" type="daterange" range-separator="-" start-placeholder="请选择开始时间"
          end-placeholder="请选择结束时间" value-format="YYYY-MM-DD" clearable />
      </el-form-item>
    </template>
    <template #button>
      <div class="flex">
        <el-button :type="data.dayIndex == 1 ? 'success' : ''" :disabled="indexStore.loading"
          @click="changeTime(1)">今日</el-button>
        <el-button :type="data.dayIndex == 2 ? 'success' : ''" :disabled="indexStore.loading"
          @click="changeTime(2)">昨日</el-button>
        <el-button :type="data.dayIndex == 3 ? 'success' : ''" :disabled="indexStore.loading"
          @click="changeTime(3)">上周</el-button>
        <el-button :type="data.dayIndex == 4 ? 'success' : ''" :disabled="indexStore.loading"
          @click="changeTime(4)">本周</el-button>
        <el-button :type="data.dayIndex == 5 ? 'success' : ''" :disabled="indexStore.loading"
          @click="changeTime(5)">本月</el-button>
        <el-button :type="data.dayIndex == 6 ? 'success' : ''" :disabled="indexStore.loading"
          @click="changeTime(6)">上月</el-button>
      </div>
    </template>
    <template #table>
      <template v-for="(item, index) in data.fields" :key="index">
        <el-table-column v-if="item.visible" :prop="item.prop" :label="item.label" :width="item.width"
          :sortable="item.sortable ? true : false" show-overflow-tooltip>
          <template #header>
            <el-tooltip v-if="item.tips" effect="dark" placement="top">
              <template #content>
                {{ item.tips }}
              </template>
              <el-icon class="ques-tips">
                <QuestionFilled />
              </el-icon>
            </el-tooltip>
            {{ item.label }}
          </template>
          <template v-if="item.prop == 'operated_id'" #default="scope">
            <div class="flex">
              <div style="width: 55px;">
                <el-tag v-if="!indexStore.is_general_agent" size="small"
                  :type="selectToLabel(indexStore.operatorArray, scope.row.operated_id, 'type', 'value') == 1 ? 'danger' : 'warning'"
                  style="font-size:10px;">
                  {{ selectToLabel(indexStore.operatorArray, scope.row.operated_id, 'type', 'value') == 1 ? '多货币' : '正常总代' }}
                </el-tag>
              </div>
              <span >{{ selectToLabel(indexStore.operatorArray, scope.row.operated_id) }}</span>
            </div>
          </template>
          <template v-if="item.prop == 'agent_id'" #default="scope">
            {{ selectToLabel(indexStore.agentArray, scope.row.agent_id) }}
          </template>
          <template v-if="item.prop == 'agent_area'" #default="scope">
            {{ selectToLabel(COUNTRY, scope.row.agent_area) }}
          </template>
          <template v-if="item.prop == 'total_bet'" #default="scope">
            <span class="colorText">{{ BigWan(scope.row.total_bet) }}</span>
          </template>
          <template v-if="item.prop == 'total_game_income'" #default="scope">
            <span class="details" :class="colorClass(scope.row.total_game_income)"
              @click="checkDetails(scope.row, 'slot_son')">
              {{ BigWan(scope.row.total_game_income) }}</span>
          </template>
          <template v-if="item.prop == 'slot_bet'" #default="scope">
            <div class="details" @click="checkDetails(scope.row, 'slot_son')">
              <span class="colorText">{{ BigWan(scope.row.slot_bet) }}</span> /
              <span :class="colorClass(scope.row.slot_game_income)">{{ BigWan(scope.row.slot_game_income) }}</span>
            </div>
          </template>
          <template v-if="item.prop == 'hundred_bet'" #default="scope">
            <div class="details" @click="checkDetails(scope.row, 'hundred_son')">
              <span class="colorText">{{ BigWan(scope.row.hundred_bet) }}</span> /
              <span :class="colorClass(scope.row.hundred_game_income)">{{ BigWan(scope.row.hundred_game_income)
                }}</span>
            </div>
          </template>
          <template v-if="item.prop == 'mine_bet'" #default="scope">
            <div class="details" @click="checkDetails(scope.row, 'mine_son')">
              <span class="colorText">{{ BigWan(scope.row.mine_bet) }}</span> /
              <span :class="colorClass(scope.row.mine_game_income)">{{ BigWan(scope.row.mine_game_income) }}</span>
            </div>
          </template>
          <template v-if="item.prop == 'agent_ratio'" #default="scope">
            {{ scope.row.agent_ratio }}%
          </template>
          <template v-if="item.prop == 'share'" #default="scope">
            <span :class="colorClass(BigTimes(BigWan(scope.row.total_game_income), BigHundred(scope.row.agent_ratio)))">
              {{ BigTimes(BigWan(scope.row.total_game_income), BigHundred(scope.row.agent_ratio)) }}
            </span>
          </template>
        </el-table-column>
      </template>
    </template>
  </SearchTable>

  <!-- 变更表头弹框 -->
  <tableHeader :dialogVisible="data.dialogVisible" :list="data.fields" @cancel="data.dialogVisible = false"
    @resetData="resetData" />

  <!-- 游戏详情 -->
  <el-dialog v-model="data.isShowDetails" width="60%" title="游戏详情" :close-on-click-modal="false" top="12vh"
    :close-on-press-escape="false" @close="onHideDetails">
    <div class="dialogMaxHeight" style="padding: 0;">
      <p class="box-title mustPass">
        【{{ data.checkedItem.agent_id }}】 {{ selectToLabel(indexStore.agentArray, data.checkedItem.agent_id) }}
        <span style="color: #666666;">{{ data.checkedItem.currency }}</span>
      </p>
      <el-tabs v-model="data.dataType" type="card" class="demo-tabs" @tab-click="handleClick"
        style="margin-top: 5px;margin-bottom: -10px;">
        <el-tab-pane label="老虎机" name="slot_son" />
        <el-tab-pane label="百人场" name="hundred_son" />
        <el-tab-pane label="MiniGame" name="mine_son" />
      </el-tabs>
      <div class="statistic " style="margin-bottom: -5px;">
        <p v-show="data.dataType == 'slot_son'">老虎机流水: <span class="marginR30"
            :class="colorClass(data.checkedItem.slot_bet)">{{ BigWan(data.checkedItem.slot_bet) }}</span>老虎机输赢: <span
            :class="colorClass(data.checkedItem.slot_game_income)">{{ BigWan(data.checkedItem.slot_game_income)
            }}</span>
        </p>
        <p v-show="data.dataType == 'hundred_son'">百人场流水: <span class="marginR30"
            :class="colorClass(data.checkedItem.hundred_bet)">{{ BigWan(data.checkedItem.slot_bet) }}</span>百人场输赢: <span
            :class="colorClass(data.checkedItem.hundred_game_income)">{{ BigWan(data.checkedItem.hundred_game_income)
            }}</span></p>
        <p v-show="data.dataType == 'mine_son'">老虎机流水: <span class="marginR30"
            :class="colorClass(data.checkedItem.mine_bet)">{{ BigWan(data.checkedItem.mine_bet) }}</span>街机输赢: <span
            :class="colorClass(data.checkedItem.mine_game_income)">{{ BigWan(data.checkedItem.mine_game_income)
            }}</span>
        </p>
      </div>
      <SearchTable :list="data.listDetails" :total="data.totalDetails" :showForm="false" :showSet="false"
        @reset="onHideDetails(true)" style="padding-top: 0px;">
        <template #form></template>
        <template #table>
          <template v-for="(item, index) in data.fieldDetails" :key="index">
            <el-table-column v-if="item.visible" :prop="item.prop" :label="item.label" :width="item.width">
              <template #header>
                <el-tooltip v-if="item.tips" effect="dark" placement="top">
                  <template #content>
                    {{ item.tips }}
                  </template>
                  <el-icon class="ques-tips">
                    <QuestionFilled />
                  </el-icon>
                </el-tooltip>
                {{ item.label }}
              </template>
              <template v-if="item.prop == 'game_id'" #default="scope">
                <div class="gameIcon">
                  <div><img class="game-icon" :src="selectToLabel(GAMEICON, scope.row.game_id)" alt=""></div>
                  {{ selectToLabel(indexStore.gameArray, scope.row.game_id) }}
                </div>
              </template>
              <template v-if="item.prop == 'game_bet'" #default="scope">
                <span class="colorText">{{ BigWan(scope.row.game_bet) }}</span>
              </template>
              <template v-if="item.prop == 'game_income'" #default="scope">
                <span :class="colorClass(scope.row.game_income)">
                  {{ BigWan(scope.row.game_income) }}</span>
              </template>
              <template v-if="item.prop == 'radio'" #default="scope">
                {{ EarningPercent(scope.row.game_bet, scope.row.game_income) }}%
              </template>
            </el-table-column>
          </template>
        </template>
      </SearchTable>
    </div>
  </el-dialog>
</template>

<script lang="ts" setup>
import { ref, reactive, toRefs, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { TabsPaneContext } from 'element-plus'
import { getMerchantReport, settlementShare } from '@/api/instrument'
import tableHeader from '@/components/tableHeader/tableHeader.vue'
import SearchTable from '@/components/SearchTable/SearchTable.vue'
import Operator, { type QueryType } from '@/components/FormItem/Operator.vue'
import { exportToExcel } from '@/utils/export'
import { throttle, selectToLabel, colorClass } from '@/utils/index'
import { GAMEICON } from '@/config/eunm'
import { COUNTRY } from '@/config/country'
import { getDateDay, getWeek, getMonth, setTimeValue } from '@/utils/time'
import { BigWan, BigHundred, BigTimes, EarningPercent } from '@/utils/math'
import { useStore } from '@/stores/index'
const indexStore = useStore()
const data = reactive({
  query: {
    page: 1,
    size: 50,
    agent_id: -1,
    operated_id: -1,
    currency_id: -1,
    date: [getDateDay(0), getDateDay(0)]
  },
  list: [],
  total: 0,
  dayIndex: 1,
  fields: [
    // Aviator属于百人，Mines属于街机，slot为老虎机
    { label: '日期', prop: 'date', width: '200', visible: true },
    { label: '上级渠道', prop: 'operated_id', width: '180', visible: true, tips: '商户的上级代理' },
    { label: '商户昵称', prop: 'agent_id', width: '120', visible: true, tips: '商户的名称' },
    { label: '地区', prop: 'agent_area', width: '100', visible: true, tips: '商户的经营区域，可更改，创建商户时的信息设定' },
    { label: '币种', prop: 'currency', width: '100', visible: true, tips: '商户游戏结算所使用的货币，不轻易更改，创建商户时的信息设定' },
    { label: 'GGR', prop: 'share', width: '150', visible: true, tips: '总输赢*商户分成比例就是商户收入' },
    { label: '分成比例', prop: 'agent_ratio', width: '120', visible: true, tips: '商户分成比例' },
    { label: '总投注用户数', prop: 'total_valid_user', width: '150', visible: true, tips: '根据筛选日期内查询商户有下注过玩家数量' },
    { label: '总投注', prop: 'total_bet', width: '', visible: true, sortable: true, tips: '根据筛选日期内查询商户的玩家下注额数量也称为玩家流水、注单额' },
    { label: '总输赢', prop: 'total_game_income', width: '', visible: true, sortable: true, tips: '根据筛选日期内查询商户的输赢情况正为盈利、负为亏损' },
    // { label: 'Slot流水/输赢', prop: 'slot_bet', width: '', visible: true, sortable: true },
    // { label: '百人场流水/输赢', prop: 'hundred_bet', width: '', visible: true, sortable: true },
    // { label: '街机流水/输赢', prop: 'mine_bet', width: '', visible: true, sortable: true },
  ],
  dialogVisible: false,
  isShowDetails: false,
  exportLoading: false,
  dataType: 'slot_son',
  checkedItem: {} as any,
  listDetails: [],
  totalDetails: 0,
  fieldDetails: [
    { label: '游戏名称', prop: 'game_id', width: '200', visible: true },
    { label: '总流水', prop: 'game_bet', width: '', visible: true, tips: '根据筛选日期内查询商户的玩家下注额数量也称为玩家流水、注单额' },
    { label: '总输赢', prop: 'game_income', width: '', visible: true, tips: '根据筛选日期内查询商户的输赢情况正为盈利、负为亏损' },
    { label: '投注用户数', prop: 'valid_user', width: '150', visible: true, tips: '今日进入游戏投注的人数，去重' },
    { label: '游戏次数', prop: 'game_count', width: '150', visible: true, tips: '今日进入此游戏的人数，去重' },
    { label: '游戏盈利率', prop: 'radio', width: '150', visible: true, tips: '投注 / 返奖  - 100%' }
  ]
})

// 商户类别 + 商户
const queryItem = (item: QueryType) => {
  data.query.agent_id = item.agent_id
  data.query.operated_id = item.operated_id
}

onMounted(async () => {
  getSearchList()
})

const getSearchList = async () => {
  data.query = setTimeValue(data.query)
  indexStore.setPageLoading(true)
  let res = await getMerchantReport(data.query)
  indexStore.setPageLoading(false)
  res.data.list?.forEach((item: any) => {
    item.date = data.query.date[0] + ' ~ ' + data.query.date[1]
    item.currency = selectToLabel(indexStore.currentArray, selectToLabel(indexStore.agentCurrency, item.agent_id)) + '(' + selectToLabel(indexStore.currentArray, selectToLabel(indexStore.agentCurrency, item.agent_id), 'type', 'value') + ')' + '-' + selectToLabel(indexStore.currentArray, selectToLabel(indexStore.agentCurrency, item.agent_id), 'remark', 'value')
  })
  data.list = res.data.list
  data.total = res.data.total
}
// 设置快捷查询时间
const changeTime = throttle((type: number) => {
  if (data.dayIndex == type) return false
  data.dayIndex = type
  switch (type) {
    case 1:
      data.query.date = [getDateDay(0), getDateDay(0)]
      break;
    case 2:
      data.query.date = [getDateDay(-1), getDateDay(-1)]
      break;
    case 3:
      data.query.date = getWeek(-1)
      break;
    case 4:
      data.query.date = getWeek(0)
      break;
    case 5:
      data.query.date = getMonth(0)
      break;
    case 6:
      data.query.date = getMonth(-1)
      break;
  }
  getSearchList()
}, 2000)

// 选择游戏tab
const handleClick = async (tab: TabsPaneContext) => {
  data.dataType = tab.paneName as string
  checkDetails(data.checkedItem, data.dataType)
}
// 详情
const checkDetails = async (row: any, type: string) => {
  data.isShowDetails = true
  data.checkedItem = row
  data.listDetails = row[type]
}

// 结算分成
const settlementSharing = (row: any) => {
  ElMessageBox.confirm(
    `是否给商户【${row.agent_id}】${selectToLabel(indexStore.agentArray, row.agent_id)}结算？`,
    '结算',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning'
    }
  )
    .then(async () => {
      let res = await settlementShare({
        id: row.id,
        status: 1
      })
      ElMessage.success('结算成功')
      getSearchList()
    })
    .catch(() => { })
}

// 导出
const getExport = async () => {
  let query = JSON.parse(JSON.stringify(data.query));
  query.page = 1
  query.size = 10000

  let res = await getMerchantReport(query);
  let dataList = res.data.list;

  let header: string[] = []
  let list: never[][] = []

  data.fields.forEach((item) => {
    header.push(item.label)
  })

  dataList.forEach((item: { [x: string]: any }, index: any) => {
    let arr: never[] = []
    data.fields.forEach((x) => {
      switch (x.prop) {
        case 'date':
          arr.push(data.query.date[0] + ' ~ ' + data.query.date[1] as never)
          break
        case 'operated_id':
          arr.push(selectToLabel(indexStore.operatorArray, item[x.prop]) as never)
          break
        case 'agent_area':
          arr.push(selectToLabel(COUNTRY, item[x.prop]) as never)
          break
        case 'agent_id':
          arr.push(selectToLabel(indexStore.agentArray, item[x.prop]) as never)
          break
        case 'currency':
          arr.push(selectToLabel(indexStore.currentArray, selectToLabel(indexStore.agentCurrency, item['agent_id'])) + '(' + selectToLabel(indexStore.currentArray, selectToLabel(indexStore.agentCurrency, item['agent_id']), 'type', 'value') + ')' as never)
          break
        case 'agent_ratio':
          arr.push(item[x.prop] + '%' as never)
          break
        case 'share':
          arr.push(BigTimes(BigWan(item['total_game_income']), BigHundred(item['agent_ratio'])) as never)
          break
        case 'total_bet':
          arr.push(BigWan(item[x.prop]) as never)
          break
        case 'total_game_income':
          arr.push(BigWan(item[x.prop]) as never)
          break
        default:
          arr.push(item[x.prop] as never)
          break
      }
    })
    list.push(arr)
  })
  exportToExcel(list, header, '商户报表')
}

// 修改页数
const changeSize = (val: number) => {
  data.query.size = val
  getSearchList()
}

const changePage = (val: number) => {
  data.query.page = val
  getSearchList()
}

// 重置表头
const resetData = (val: any) => {
  data.fields = val
}

// 重置
const OperatorRef = ref<any>()
const onHideDetails = (show: boolean) => {
  if (show) {
    data.query = {
      page: 1,
      size: 50,
      agent_id: -1,
      operated_id: -1,
      currency_id: -1,
      date: [getDateDay(0), getDateDay(0)]
    }
    getSearchList()
    OperatorRef.value.onHideDetails()
  }
}
</script>

<style scoped lang="scss"></style>